import urllib.request as request
import datetime

from datetime import timedelta
'''
获取交易日
'''
class GetTransactionDay():

    def stock_get_date_type(self,query_date):
        """
        获取日期类型
        :param query_date: 日期，如 2020-10-01
        :return 0:工作日，1:周末，2:假日，-1:出错
        """
        query_date = query_date.strftime('%Y-%m-%d')
        url = 'http://tool.bitefu.net/jiari/?d=' + query_date
        resp = request.urlopen(url, timeout=3)
        content = resp.read()
        if content:
            try:
                day_type = int(content)
            except ValueError:
                return -1
            else:
                return day_type

        return -1

    def stock_is_trade_date(self,query_date):
        """
        是否为 交易日
        :param query_date: 日期，如 2020-10-01
        :return: 1:是，0:不是
        """
        weekday = query_date.isoweekday()
        if weekday <= 5 and self.stock_get_date_type(query_date) == 0:
            return True
        else:
            return False


    def get_trade_date(self,query_date):
        if self.stock_is_trade_date(query_date):
            return query_date
        else:
            yes_time = query_date + timedelta(days=-1)
            return  self.get_trade_date(yes_time)

    #获取从今天开始计算的交易日期
    def get_now_trade_date(self):
        h = datetime.datetime.now().hour
        stdate = datetime.date.today()
        date =self.get_trade_date(stdate)
        boo = stdate==date
        if h > 9 and h < 19  and boo:
            v = True
        else:
            v = False
        return  date,v

    def getNextDay(self,bs, todate):
        yes_time = todate + timedelta(days=-1)
        day = yes_time.strftime('%Y-%m-%d')
        rs = bs.query_all_stock(day=day)
        if rs.next() == False:
            return  self.getNextDay(bs, yes_time)
        else:
            return rs,yes_time




if __name__ == '__main__':
    GetTransactionDay  = GetTransactionDay()
    bjdate = datetime.date.today()
    print(GetTransactionDay.get_now_trade_date())

